lvalue method
Stanislav Blinov
stanislav.blinov at gmail.com
Fri Oct 8 02:09:40 PDT 2010
Benjamin Thaut wrote:
> Hi, I'm writing a vec4 math struct and I have a method of which the
> return value has to be a lvalue so I wonder which is the correct way to
> do this:
>
> vec4 Normalize() const { ... } //won't work, not a lvalue
>
> ref vec4 Normalize() const {
> vec4 temp;
> ...
> return temp;
> } //will this lead to a segfault or not?
>
> ref vec4 Normalize() const {
> vec4* temp = new vec4;
> ...
> return *temp;
> } //ugly, don't want to allocate anything on the heap
>
> auto ref vec4 Normalize() const {
> vec4 temp;
> ...
> return temp;
> } //will this lead to a segfault?
>
> Or do I need to do it totaly in some other way?
>
If you need to normalize vector inplace, then your Normalize() shouldn't
be const:
ref vec4 Normalize() {
// code
return this;
}
If you want to return a normalized copy of vector, the you don't need ref:
vec4 Normalize() const {
vec4 temp;
//...
return temp;
}
More information about the Digitalmars-d-learn
mailing list