3

This is what I'm trying to accomplish:

struct test{};

const test returnconst(){
    return test();
}

test returnnonconst(){
    return test();
}

int main(){
          test t1=returnnonconst();
    const test t2=returnnonconst();
          test t3=returnconst();  //I want this to be a compile error
    const test t4=returnconst();
}

The compiler accepts all of the four return* calls. I understand that in the third call a copy of the object is constructed, but I want instead to force the caller of returnconst to store the value as const. Are there workaround to this?

Lorenzo Pistone
  • 5,028
  • 3
  • 34
  • 65
  • 1
    Why would you want this to be an error? If the caller is taking a copy of what's returned from the function, then the caller get's to decide if it's const/not, no? – Benj May 09 '12 at 19:06
  • @Benj test would be a template class which proxies an object type (it catches and relays calls to operators). I'm trying to avoid transferring the constness of such object in the template argument of the proxy, as it would complicate some other part of the proxy code. Instead I want to have a const proxy if the object is const. returnconst and returnnonconst are actually the creator of the proxies (they take an object reference): they would be overloads, one for const objects, the other for non const (and they would return respectively a const proxy and a non const proxy). – Lorenzo Pistone May 09 '12 at 19:14

3 Answers3

3

You're returning by value. You're creating a copy of a const. So you're basically saying you don't want to be able to make copies of const:

struct test { private: test(const test& other); };

The previous code doesn't work, you get tons of other errors. It's just not possible :)

It doesn't work not because you restrict it from creating copies of const objects, but there's no way to enforce that the newly created object is also const.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

There is no way to do that. Why do you want to do it? What are you trying to achieve?

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
0

your issue here is that it is returning a const object and invoking your copy assignment or constructor to create a by value copy of a new non const object. You could disable by value copy construction and force users to use a reference assignment but that may be annoying.

rerun
  • 25,014
  • 6
  • 48
  • 78