0
votes

suppose I have a class like this and I would like to create a string with a specific capacity. I tried doing the following but that did not work. Any suggestions ? I know I could do it in the constructor but would like to do it during the declaration if possible.

class foo
{
 std::string bar = std::string().resize(45);
}

I get the error

main.cpp: In function 'int main()': main.cpp:8:46: error: conversion from 'void' to non-scalar type 'std::__cxx11::string {aka std::__cxx11::basic_string}' requested std::string test = std::string().resize(45);

2

2 Answers

0
votes

In c++11 we have new feature called move constructor so

string str = string(); 

doesn't cause extra time.

http://en.cppreference.com/w/cpp/language/move_constructor

with move constructor, the program would directly use the address of the temporary constructed string after = sign, without making a copy.

The problem is that resize()function in c++ actually returns void


basic_string( size_type count, 
              CharT ch, 
              const Allocator& alloc = Allocator() );

This constructor might be something you are directly interested in.

You can do something with

std::string str(45, ' ');
0
votes

In C++, you probably don't want to "chain" methods unless previous methods have the correct return type.

As suggested by @James Maa, you can do simply use the constructor.