-1

In my class I have the following c'tor:

std::string obj_from;
std::string obj_to;


travel (std::string &from, std::string &to) : obj_from(from), obj_to(to)
{}

But since I'm giving a reference will the new object point to the given string? I mean will the string be shared between two things?

  • 1
    What are `obj_from` and `obj_to`? Just plain `std::string`s, or maybe references? – HolyBlackCat Aug 04 '20 at 10:08
  • @HolyBlackCat plain string like this: std::string obj_from; –  Aug 04 '20 at 10:09
  • You need to show the declaration of your class to answer this question. `from` and `to` go out of scope once the constructor is done, so their types only prevent a copy (or not), but change nothing about `obj_from`. – Ext3h Aug 04 '20 at 10:09
  • 2
    since you are using the initializer list without some special cast, you will invoke the copy constructor, so `obj_from` `obj_to` will contains 2 new strings – Alberto Sinigaglia Aug 04 '20 at 10:09
  • 1
    `travel` contains two copies. That are not references. – Thomas Sablik Aug 04 '20 at 10:13
  • It's arguments are reference notice the & sign @ThomasSablik –  Aug 04 '20 at 10:17
  • When constructed this way, it is only "shared" if your class also stores a _reference_ (or similar, _e.g._ `std::reference_wrapper`) – paddy Aug 04 '20 at 10:17
  • `from` and `to` are references but `obj_from` and `obj_to` aren't. `obj_from` and `obj_to` are copies of the objects `from` and `to` pointed to. – Thomas Sablik Aug 04 '20 at 10:18

2 Answers2

2

In general the answer is no. You create new, separate strings.

Pre-C++11, std::string implementations were allowed to share the underlying character array between several strings, and some compilers did it, but it's no longer the case.

If your strings are so long that you need them to share memory, you could use something like std::shared_ptr<std::string>.


FYI, a better way to write this constructor would be:

travel(std::string from, std::string to)
    : obj_from(std::move(from)), obj_to(std::move(to))
{}

Unlike the one you use, it lets you pass temporary and/or const strings as parameters, while avoiding unnecessary copies.

travel a("foo", "bar");
const std::string x = "baz";
travel b(x, x);
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
1

No, in this line

travel (std::string &from, std::string &to) : obj_from(from), obj_to(to) {} 

you call the constructors of class members (copy constructors in this case). They create two different objects - obj_from and obj_to. The only limitation is that you can provide only lvalues to to the travel constructor. To make it universal you can convert it to:

travel (const std::string &from, const std::string &to) : obj_from(from), obj_to(to) {}
Vasilij
  • 1,861
  • 1
  • 5
  • 9